package com.example.demo.config;

import org.springframework.boot.Banner;
import org.springframework.boot.ResourceBanner;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class AppListener implements ApplicationListener<ApplicationEvent> {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            Resource resource = new ClassPathResource("banner.txt");
            if (resource.exists()) {
                Banner banner = new ResourceBanner(resource);
                ConfigurableEnvironment environment =
                    ((ApplicationReadyEvent) event).getApplicationContext().getEnvironment();
                try {
                    environment.getSystemProperties().put("localhost", InetAddress.getLocalHost().getHostAddress());
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                banner.printBanner(environment,
                    ((ApplicationReadyEvent) event).getSpringApplication().getMainApplicationClass().getClass(),
                    System.out);
            }
        }
    }

}
